import express from 'express';
import db from '../config/db.js';
import { generateTokenPair, verifyRefreshToken, getRefreshTokenStore } from '../middleware/auth.js';
import { sendSMS, verifySMSCode, clearSMSCode } from '../services/smsService.js';

const router = express.Router();

// 发送短信验证码接口
router.post('/send-code', async (req, res) => {
  const { phone } = req.body;

  try {
    const result = await sendSMS(phone);
    res.json(result);
  } catch (error) {
    console.error('发送短信失败 - 错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      statusText: error.response?.statusText
    });
    res.status(500).json({ success: false, message: '发送验证码失败' });
  }
});

// 登录接口：按手机号与密码查询
router.post('/login', async (req, res) => {
  const phone = String(req.body?.phone ?? '').trim();
  const password = String(req.body?.password ?? '').trim();

  if (!phone || !password) {
    return res.status(400).json({ message: '缺少必需参数: phone 或 password' });
  }

  try {
    const sql = 'SELECT id, phone FROM user WHERE phone = ? AND password = ? LIMIT 1';
    const rows = await new Promise((resolve, reject) => {
      db.pool.query(sql, [phone, password], (err, result) => {
        if (err) return reject(err);
        resolve(Array.isArray(result) ? result : []);
      });
    });

    if (!rows || rows.length === 0) {
      return res.status(401).json({ message: '手机号或密码不正确' });
    }

    const user = rows[0];
    const tokenPair = generateTokenPair(user.id, user.phone);
    
    return res.json({ 
      id: user.id, 
      phone: user.phone, 
      ...tokenPair
    });
  } catch (error) {
    console.error('登录查询错误:', error);
    return res.status(500).json({ message: '查询失败', error: error?.message || String(error) });
  }
});

// 短信登录接口：验证短信验证码并登录
router.post('/sms-login', async (req, res) => {
  const phone = String(req.body?.phone ?? '').trim();
  const code = String(req.body?.code ?? '').trim();

  if (!phone || !code) {
    return res.status(400).json({ message: '缺少必需参数: phone 或 code' });
  }

  try {
    // 1) 验证短信验证码
    const verifyResult = verifySMSCode(phone, code);
    if (!verifyResult.success) {
      return res.status(400).json({ message: verifyResult.message });
    }

    // 2) 查找用户是否存在
    const checkSql = 'SELECT id, phone FROM user WHERE phone = ? LIMIT 1';
    const userRows = await new Promise((resolve, reject) => {
      db.pool.query(checkSql, [phone], (err, result) => {
        if (err) return reject(err);
        resolve(Array.isArray(result) ? result : []);
      });
    });

    if (userRows.length === 0) {
      return res.status(404).json({ message: '该手机号未注册，请先注册' });
    }

    // 3) 登录成功
    const user = userRows[0];
    const tokenPair = generateTokenPair(user.id, user.phone);
    
    return res.json({ 
      message: '登录成功', 
      id: user.id, 
      phone: user.phone, 
      ...tokenPair
    });
  } catch (error) {
    console.error('短信登录错误:', error);
    return res.status(500).json({ message: '登录失败', error: error?.message || String(error) });
  }
});

// 注册接口：先查重手机号，验证短信验证码，不存在则插入
router.post('/register', async (req, res) => {
  const phone = String(req.body?.phone ?? '').trim();
  const password = String(req.body?.password ?? '').trim();
  const code = String(req.body?.code ?? '').trim();

  if (!phone || !password) {
    return res.status(400).json({ message: '缺少必需参数: phone 或 password' });
  }

  if (!code) {
    return res.status(400).json({ message: '缺少验证码' });
  }

  try {
    // 1) 验证短信验证码
    const verifyResult = verifySMSCode(phone, code);
    if (!verifyResult.success) {
      return res.status(400).json({ message: verifyResult.message });
    }

    // 2) 查重手机号
    const checkSql = 'SELECT id FROM user WHERE phone = ? LIMIT 1';
    const existsRows = await new Promise((resolve, reject) => {
      db.pool.query(checkSql, [phone], (err, result) => {
        if (err) return reject(err);
        resolve(Array.isArray(result) ? result : []);
      });
    });
    if (existsRows.length > 0) {
      return res.status(409).json({ message: '该手机号已注册' });
    }

    // 3) 插入用户数据
    const insertSql = 'INSERT INTO user (phone, password) VALUES (?, ?)';
    const insertResult = await new Promise((resolve, reject) => {
      db.pool.query(insertSql, [phone, password], (err, result) => {
        if (err) return reject(err);
        resolve(result);
      });
    });

    return res.json({ message: '注册成功', id: insertResult?.insertId, phone });
  } catch (error) {
    console.error('注册错误:', error);
    return res.status(500).json({ message: '注册失败', error: error?.message || String(error) });
  }
});

// 刷新访问令牌接口
router.post('/refresh', async (req, res) => {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.status(400).json({ message: '缺少刷新令牌' });
  }

  try {
    // 验证刷新令牌
    const decoded = verifyRefreshToken(refreshToken);
    if (!decoded) {
      return res.status(401).json({ message: '刷新令牌无效或已过期' });
    }

    // 生成新的token对
    const newTokenPair = generateTokenPair(decoded.userId, decoded.phone);
    
    // 删除旧的刷新令牌
    const refreshTokenStore = getRefreshTokenStore();
    refreshTokenStore.delete(refreshToken);

    return res.json(newTokenPair);
  } catch (error) {
    console.error('刷新令牌错误:', error);
    return res.status(401).json({ message: '刷新令牌无效或已过期' });
  }
});

// 登出接口
router.post('/logout', (req, res) => {
  // 这里可以添加黑名单机制，将token加入黑名单
  res.json({ message: '登出成功' });
});

export default router;
